import { observer } from 'mobx-react'

import React, { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import type { PopconfirmProps } from 'antd'
import {
  Form,
  Input,
  Select,
  DatePicker,
  Button,
  Row,
  Col,
  Divider,
  Table,
  Badge,
  Space,
  Popconfirm,
  message
} from 'antd'
import type { ColumnsType } from 'antd/es/table'
const { RangePicker } = DatePicker

interface MenuItem {
  key: string
  name: string // 菜单名称
  order: number // 排序
  icon?: string // 图标(可有可无)
  route: string // 路由
  menuType: string // 菜单类型
  cache: '开启' | '关闭'
  authKey: string // 权限标识
  status: '正常' | '禁用'
  operator: string // 操作人
  time: string // 操作时间
  children?: MenuItem[]
}

const initialData: MenuItem[] = [
  {
    key: '1',
    name: '系统菜单',
    order: 1,
    icon: '', // 暂无图标
    route: '/system',
    menuType: '根菜单',
    cache: '开启',
    authKey: 'sys_gate',
    status: '正常',
    operator: 'admin',
    time: '2022-02-20 13:50:15',
    children: [
      {
        key: '1-1',
        name: '设置',
        order: 1,
        icon: '',
        route: '/system/set',
        menuType: '左菜单',
        cache: '开启',
        authKey: 'sys_gate1',
        status: '禁用',
        operator: 'admin',
        time: '2022-01-29 13:20:10',
      },
      {
        key: '1-2',
        name: '企业管理',
        order: 2,
        icon: '',
        route: '/system/computer',
        menuType: '左菜单',
        cache: '开启',
        authKey: 'sys_gate2',
        status: '禁用',
        operator: 'admin',
        time: '2022-01-27 19:21:23',
        children: [
          {
            key: '1-2-1',
            name: '菜单管理',
            order: 3,
            icon: '',
            route: '/system/computer/menu',
            menuType: '按钮',
            cache: '开启',
            authKey: 'sys_gate3',
            status: '禁用',
            operator: 'admin',
            time: '2022-01-20 22:51:34',
          },
          {
            key: '1-2-2',
            name: '角色管理',
            order: 3,
            icon: '',
            route: '/system/computer/roule',
            menuType: '按钮',
            cache: '开启',
            authKey: 'sys_gate4',
            status: '正常',
            operator: 'admin',
            time: '2022-01-11 17:21:10',
          },
        ],
      },
    ],
  },
  {
    key: '2',
    name: '日志管理',
    order: 1,
    icon: '',
    route: '/s12312',
    menuType: '左菜单',
    cache: '关闭',
    authKey: 'sys_gate8',
    status: '禁用',
    operator: 'admin',
    time: '2021-11-25 17:34:47',
    children: [
      {
        key: '2-1',
        name: '字典管理',
        order: 1,
        icon: '',
        route: '/s1231234',
        menuType: '左菜单',
        cache: '关闭',
        authKey: 'sys_gate9',
        status: '正常',
        operator: 'admin',
        time: '2021-10-27 03:51:49',
      },
    ],
  },
]

const MenuManagement: React.FC = () => {
  // 是否展开更多搜索项
  const [expand, setExpand] = useState(false)
  const [expandedRowKeys, setExpandedRowKeys] = useState<string[]>([])
  // 表格数据
  const [data, setData] = useState<MenuItem[]>(initialData)
  const navigate = useNavigate()

  // 表格列
  const columns: ColumnsType<MenuItem> = [
    {
      title: '菜单名称',
      dataIndex: 'name',
      key: 'name',
      width: 160
    },
    {
      title: '排序',
      dataIndex: 'order',
      key: 'order',
      width: 80,
      align: 'center',
    },
    {
      title: '图标',
      dataIndex: 'icon',
      key: 'icon',
      width: 80,
      align: 'center',
      render: (icon) => icon ? <img src={icon} alt="" style={{ width: 20 }} /> : <span style={{ color: '#ccc' }}>无</span>,
    },
    {
      title: '路由',
      dataIndex: 'route',
      key: 'route',
      width: 120
    },
    {
      title: '菜单类型',
      dataIndex: 'menuType',
      key: 'menuType',
      width: 120
    },
    {
      title: '缓存',
      dataIndex: 'cache',
      key: 'cache',
      width: 80,
      align: 'center',
    },
    {
      title: '权限标识',
      dataIndex: 'authKey',
      key: 'authKey',
      width: 120
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      align: 'center',
      render: (status) => {
        const color = status === '正常' ? 'green' : 'red'
        return (
          <Space>
            <Badge color={color} />
            <span>{status}</span>
          </Space>
        )
      },
    },
    {
      title: '操作人',
      dataIndex: 'operator',
      key: 'operator',
      width: 120,
    },
    {
      title: '操作时间',
      dataIndex: 'time',
      key: 'time',
      width: 160
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 200,
      render: (_, record) => {
        return (
          <div className='table-cell-actions'>
            <Button type="link" onClick={() => handleCreate(record)}>新增</Button>
            <Button type="link" onClick={() => handleEdit(record)}>修改</Button>
            {record.status === '禁用' ? (
              <Button type="link" onClick={() => handleEnable(record)}>
                启用
              </Button>
            ) : (
              <Button type="link" onClick={() => handleDisable(record)}>
                禁用
              </Button>
            )}
            <Popconfirm
              key="delete"
              placement="topRight"
              title="确定要删除吗?"
              onConfirm={handleConfirm}
              onCancel={handleCancel}
              okText="确定"
              okType="danger"
              cancelText="取消"
            >
              <Button
                type="link"
                danger
                key="delete"
              >
                删除
              </Button>
            </Popconfirm>
        </div>
        )
      },
    },
  ]
  const handleConfirm: PopconfirmProps['onConfirm'] = (e) => {
    console.log(e)
    message.success('点击确定')
  }
  const handleCancel: PopconfirmProps['onCancel'] = (e) => {
    console.log(e)
    message.error('点击取消')
  }
  // 递归获取所有菜单的 key
  const getAllKeys = (menuList: MenuItem[]): string[] => {
    let keys: string[] = []
    menuList.forEach((item) => {
      keys.push(item.key)
      if (item.children) {
        keys = keys.concat(getAllKeys(item.children))
      }
    })
    return keys
  }
  // 切换展开/折叠
  const toggleExpand = () => {
    if (!expand) {
      // 展开所有
      setExpandedRowKeys(getAllKeys(data))
    } else {
      // 折叠所有
      setExpandedRowKeys([])
    }
    setExpand(!expand)
  }
  // 点击查询
  const onFinish = (values: any) => {
    console.log('查询参数: ', values)
  }
  // 点击重置
  const onReset = () => {
    console.log('重置搜索')
    // form.resetFields()
    // 重新拉数据
  }
  // 新增
  const handleCreate = (record: MenuItem) => {
    navigate('/setting/enterpriseManagement/menuManagement/add')
  }
  // 修改
  const handleEdit = (record: MenuItem) => {
    console.log('修改', record)
  }
  // 启用
  const handleEnable = (record: MenuItem) => {
    console.log('启用', record)
  }
  // 禁用
  const handleDisable = (record: MenuItem) => {
    console.log('禁用', record)
  }
  // 删除
  const handleDelete = (record: MenuItem) => {
    console.log('删除', record)
  }

  return (
    <div className="app-container">
      {/* 搜索表单 */}
      <div className="filterForm">
        <Form
          layout="inline"
          onFinish={onFinish}
        >
            <Form.Item label="菜单名称" name="name">
              <Input placeholder="请输入菜单名称" />
            </Form.Item>
            <Form.Item label="路由地址" name="route">
              <Input placeholder="请输入路由地址" />
            </Form.Item>
            <Form.Item label="菜单类型" name="menuType">
              <Select placeholder="全部">
                <Select.Option value="">全部</Select.Option>
                <Select.Option value="根菜单">根菜单</Select.Option>
                <Select.Option value="左菜单">左菜单</Select.Option>
                <Select.Option value="按钮">按钮</Select.Option>
              </Select>
            </Form.Item>
            <Form.Item label="权限标识" name="authKey">
              <Input placeholder="请输入权限标识" />
            </Form.Item>
            <Form.Item label="状态" name="status">
              <Select placeholder="全部">
                <Select.Option value="">全部</Select.Option>
                <Select.Option value="正常">正常</Select.Option>
                <Select.Option value="禁用">禁用</Select.Option>
              </Select>
            </Form.Item>
            <Form.Item label="操作人" name="name">
              <Input placeholder="请输入操作人账号" />
            </Form.Item>
            <Form.Item label="操作时间" name="time">
              <RangePicker placeholder={['开始日期', '结束日期']} />
            </Form.Item>
          </Form>
          <div className="rightAction">
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button onClick={onReset}>重置</Button>
          </div>
      </div>
      <div>
        <Button type="primary" style={{ marginRight: 16 }} onClick={() => handleCreate({} as MenuItem)}>
          + 新增
        </Button>
        <Button onClick={toggleExpand}>
          {expand ? '折叠' : '展开'}
        </Button>
      </div>

      {/* Tree table */}
      <Table<MenuItem>
        columns={columns}
        dataSource={data}
        rowKey="key"
        pagination={{ pageSize: 9 }}
        tableLayout="fixed"
        scroll={{ x: 1200 }}
        expandable={{
          expandedRowKeys,
          onExpand: (expanded, record) => {
            setExpandedRowKeys((prevKeys) => {
              return expanded
                ? [...prevKeys, record.key]
                : prevKeys.filter((key) => key !== record.key)
            });
          },
        }}
      />
    </div>
  )
}

export default observer(MenuManagement)